package generic;
import java.text.NumberFormat;
import java.util.Locale;

public class PublisherClient {

	private Publisher publisher;
	private StringBuilder builder;
	private NumberFormat nfId = NumberFormat.getNumberInstance(Locale.GERMAN);
	private NumberFormat nfTime = NumberFormat.getNumberInstance(Locale.GERMAN);
	

	public PublisherClient(Publisher publisher) {
		super();
		this.publisher = publisher;
		builder = new StringBuilder();
		nfId.setMinimumIntegerDigits( 3 );
		nfTime.setMinimumFractionDigits( 3 );
	}
	
	public void send() {

		builder.append("MessageID;SendDuration;TimeSinceLastSend");
		builder.append(System.lineSeparator());
        // send events
    	for (int messsageId = 1; messsageId < 1001; messsageId++) {
	    	long beforeSend = System.nanoTime();
	    	String message = String.valueOf(messsageId) + ";" + String.valueOf(beforeSend); 	
	    	boolean isSuccess = publisher.send(message);
	    	long afterSend = System.nanoTime();
	    	
	    	// write to log
	    	builder.append(nfId.format(messsageId)).append(";");
	    	builder.append(nfTime.format((double)(afterSend - beforeSend) / 1000000));
	    	builder.append(System.lineSeparator());
	    	
	    	// print log
    		if (messsageId % 10 == 0) {
        		System.out.print(builder.toString());
        		builder.delete(0, builder.length());
        	}
    		
	    	try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	    	
	    	if (!isSuccess) {
	    		break;
	    	}
    	}
    	Runtime.getRuntime().exit(1);
    }
	
}
